<!-- 基本使用方法 -->
<!-- <template>
  <div>
    <h1>导出 Excel 示例</h1>
    <button @click="exportExcel">导出 Excel</button>
    <table>
      <thead>
        <tr>
          <th>姓名</th>
          <th>年龄</th>
          <th>城市</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(item, index) in tableData" :key="index">
          <td>{{ item.name }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.city }}</td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
import * as XLSX from 'xlsx'

export default {
  name: "ExportExcel",
  data() {
    return {
      tableData: [
        { name: "张三", age: 25, city: "北京" },
        { name: "李四", age: 30, city: "上海" },
        { name: "王五", age: 28, city: "广州" },
      ],
    };
  },
  methods: {
    exportExcel() {
      // 创建一个工作簿
      const wb = XLSX.utils.book_new();

      // 创建一个工作表
      const ws_data = [
        ["姓名", "年龄", "城市"], // 表头
        ...this.tableData.map((item) => [item.name, item.age, item.city]), // 表格数据
      ];

      const ws = XLSX.utils.aoa_to_sheet(ws_data);

      // 将工作表添加到工作簿
      XLSX.utils.book_append_sheet(wb, ws, "Sheet1");

      // 导出 Excel 文件
      XLSX.writeFile(wb, "exported_data.xlsx");
    },
  },
};
</script>

<style scoped>
table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 20px;
}

th,
td {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: left;
}
</style> -->







<!-- 封装使用方法 -->
<template>
  <div>
    <h1>导出 Excel 示例</h1>
    <button @click="exportExcel">导出 Excel</button>
    <table>
      <thead>
        <tr>
          <th>姓名</th>
          <th>年龄</th>
          <th>城市</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(item, index) in tableData" :key="index">
          <td>{{ item.name }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.city }}</td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
import { exportExcel } from "../utils/useExcle"; // 引入封装的函数

export default {
  name: "ExportExcel",
  data() {
    return {
      tableData: [
        { name: "张三", age: 25, city: "北京" },
        { name: "李四", age: 30, city: "上海" },
        { name: "王五", age: 28, city: "广州" },
      ],
    };
  },
  methods: {
    exportExcel() {
      const fieldMapping = {
        name: "姓名",
        age: "年龄",
        city: "城市"
      }; // 数据字段与表头字段的映射关系
      const fileName = "exported_data"; // 文件名

      // 调用封装的导出函数
      exportExcel(this.tableData, fieldMapping, fileName);
    },
  },
};
</script>
